package server;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;

import Logic.SendMail;
/**
 * this class imlements thread that check if subscriber need to return book tommarow and then sending mail 
 * @author Ron Shenkerman
 * @author Gabi Revah
 * @author Aviad Almog
 * @author Ivan Onyshchenko
 */
public class CheckLending implements Runnable{

	private static final int oneday=86400000;
	int date,flag,j;
	String str,subscriberid,mailto;
	Date returndate,today1,date1;
	Statement stmt,stm;
	

	@SuppressWarnings("deprecation")
	@Override
	/**
	 * run the thread
	 */
	public void run() {
		
		j=0;
		while(EchoServer.echoserveron){
			try 
				{
			//	System.out.println(j);	
				j++;
			System.out.println("getting book detail for viewing");
			//Statement stmt,stmt1;
			SQLConnection conn = new  SQLConnection();
			stmt = conn.getConnection().createStatement();
			
			String y="yes";
			java.util.Date today = new java.util.Date();
			java.sql.Date timestamp = new java.sql.Date(today.getTime());//the date today
			ResultSet rs= stmt.executeQuery("SELECT * FROM db1.lending WHERE lending.lend='"+y+"';");
			rs.next();
			try {
					date=timestamp.getDate();
					Date myDate = new Date(today.getYear(),today.getMonth(),today.getDay());	
					myDate.setDate(date+1);
					//Date d = new Date(date1.getDate());
					rs.previous();
					  while(rs.next()){ 
						  subscriberid=rs.getString(2);
						Statement stmt1 = conn.getConnection().createStatement();
							ResultSet rs1= stmt1.executeQuery("SELECT * FROM db1.subscriber WHERE subscriber.ID='"+subscriberid+"';");
							rs1.next();
							mailto=rs1.getString(2);
						  			returndate=rs.getDate(5);//the date to return the book
						  			//System.out.println("returndate:"+returndate+"");
						  			//System.out.println("today:"+myDate+"");
									flag=myDate.compareTo(returndate);
									//System.out.println(j);	
										if(flag==0){
										SendMail sm= new SendMail(mailto,returndate); 
										System.out.println("mail sent");
										}
								}
						
					}
						catch (SQLException e)
								{	
								e.printStackTrace();
								}
			
	}
		catch (Exception ex )
		{
			ex.printStackTrace();
			}
			try 
			{
				Thread.sleep(oneday);
				
			} 
			catch (InterruptedException e) 
			{
				e.printStackTrace();
			}
	
		}
	}

	
}
